package business

import (
	"crypto/md5"
	"encoding/hex"
	"gitee.com/smallow/srpc/infrastructure/conf"
	"gitee.com/smallow/srpc/infrastructure/model"
	"gorm.io/gorm"
	"time"
)

func SaveDepartment(department *model.Department) error {
	if department.ID != 0 {
		return conf.GetMysqlDB().Updates(department).Error
	} else {
		err := conf.GetMysqlDB().Create(department).Error
		if err != nil {
			return err
		}
		return nil
	}
}

func SaveBatches(department []*model.Department) error {
	err := conf.GetMysqlDB().CreateInBatches(department, len(department)).Error
	if err != nil {
		return err
	}
	return nil
}

func SaveDepartmentDA(departmentDA *model.Account) error {
	if departmentDA.ID != 0 {
		return conf.GetMysqlDB().Updates(departmentDA).Error
	} else {
		//return conf.GetMysqlDB().Create(departmentDA).Error
		err := conf.GetMysqlDB().Transaction(func(tx *gorm.DB) error {
			if err := tx.Create(departmentDA).Error; err != nil {
				return err
			}
			accountRole := &model.AccountRole{
				AccountId: departmentDA.ID,
				RoleId:    1,
				AppId:     departmentDA.AppID,
			}
			if err := tx.Create(accountRole).Error; err != nil {
				return err
			}
			return nil
		})
		if err != nil {
			return err
		}
	}
	return nil
}

func FindDepartment(departmentID, companyID int) (users []model.User, childDepartments []model.DepartmentShort, err error) {
	//查询该部门下的员工
	err = conf.GetMysqlDB().Table("is_employee").Where(model.Employee{DepartmentId: departmentID, CompanyId: companyID}).Find(&users).Error
	//查找部门下的子部门
	err = conf.GetMysqlDB().Table("is_department").Where(model.Department{ParentID: departmentID, CompanyID: companyID}).Find(&childDepartments).Error
	if err != nil {
		return nil, nil, err
	}
	return users, childDepartments, nil
}

func UpdateDepartment(department map[string]interface{}, id int) error {
	err := conf.GetMysqlDB().Table("is_department").Where("id = ?", id).Updates(department).Error
	return err
}

func DeleteDepartment(id int, appId string) error {
	err := conf.GetMysqlDB().Transaction(func(tx *gorm.DB) error {
		//删除部门
		query := &model.Department{BaseModel: model.BaseModel{ID: id}}
		err := tx.Where("app_id = ?", appId).Delete(query).Error
		//删除部门账号
		err = tx.Where("body_id = ? and app_id = ?", id, appId).Delete(&model.Account{}).Error
		//删除部门下的人
		err = tx.Where("department_id = ? and app_id = ?", id, appId).Delete(&model.Employee{}).Error
		//删除部门下人员的账号
		t := time.Now().Format("2006-01-02 15:04:05")
		param := []interface{}{
			t, id, appId,
		}
		err = tx.Exec("UPDATE is_employee a  LEFT JOIN is_account b on a.id=b.body_id SET b.delete_at=? WHERE department_id =? AND body_type=2 AND a.app_id=?", param...).Error
		return err
	})
	return err
}

//生成32位md5字串
func GetMd5String(s string) string {
	h := md5.New()
	h.Write([]byte(s))
	return hex.EncodeToString(h.Sum(nil))
}
